//
//  EFARootVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFARootVC.h"
#import "EFAMsgVC.h"
#import "EFADeviceVC.h"
#import "EFAAppVC.h"
#import "EFAMoreVC.h"
#import "EFAPjtManagerVC.h"
#import "EFAModel.h"
#import <JPUSHService.h>
#import "GlobalHeader.h"
#import "AppDelegate.h"
#import "EFANoticeDetailVC.h"
#import "ApiManager.h"
#import "EFAUtyPromptVC.h"
#import "ProjectListView.h"


@interface EFARootVC ()<UITabBarControllerDelegate>
@property (nonatomic, strong) UINavigationController *navMsgVC;
@property (nonatomic, strong) UINavigationController *navDeviceVC;
@property (nonatomic, strong) UINavigationController *navAppVC;
@property (nonatomic, strong) UINavigationController *navMoreVC;
@property (nonatomic, strong) UINavigationController *navEmptyVC;
@end

@implementation EFARootVC
#pragma mark - life cycle
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EFAGlobalNotiPushProcess object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 代理
    __weak typeof(self) weakSelf = self;
    self.delegate = weakSelf;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushProcessHandle:) name:EFAGlobalNotiPushProcess object:nil];
    // 极光推送
    // 这里主要是为了之前下载APP的用户，直接进入APP，导致没有绑定别名而做的措施
    [[EFAModel sharedInstance] CheckJPUSHAlias];
    
    // 配置页面
    [self setupSubViewsWithRefresh:NO];
}
- (void)setupSubViewsWithRefresh:(BOOL)refresh {
    NSArray *array = nil;
    if (refresh) {
        array = @[self.navMsgVC, self.navEmptyVC, self.navAppVC, self.navMoreVC];
    } else {
        array = @[self.navMsgVC, self.navDeviceVC, self.navAppVC, self.navMoreVC];
    }
    [self setViewControllers:array animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 启动的时候查看是否有推送
    [self pushProcessHandle:nil];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 检查是否显示用户告警书
    if ([EFAModel sharedInstance].isNewVersion) {
        [self jumpToUserNotice];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UITabBarControllerDelegate
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    if (viewController == self.navEmptyVC) {
        [self requestRefreshUserInfo];
    }
}
#pragma mark - event response
#pragma mark - private methods
- (void)pushProcessHandle:(NSNotification *)notification {
    NSDictionary *dic = ((AppDelegate *)[UIApplication sharedApplication].delegate).pushDictionary;
    if (!dic) {
        return;
    }
    ((AppDelegate *)[UIApplication sharedApplication].delegate).pushDictionary = nil;
    NSDictionary *efairy = dic[@"efairy"];
    if (efairy && [efairy[@"type"] integerValue] == 0) {        // 公告推送
        [self jumpToNoticeDetailWithNotId:[efairy[@"id"] integerValue]];
    } else if (efairy && [efairy[@"type"] integerValue] == 1) { // 角色变更推送
        [self jumpToPromptWithRoleId:[efairy[@"id"] integerValue]];
    }
}
- (void)jumpToNoticeDetailWithNotId:(NSInteger)noticeId {
    EFANoticeDetailVC *vc = [[EFANoticeDetailVC alloc] init];
    vc.noticeId = noticeId;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    UIViewController *topmostVC = [self topViewController];
    [topmostVC presentViewController:nav animated:YES completion:nil];
}
- (void)jumpToPromptWithRoleId:(NSInteger)roleId {
    NSString *roleName = [[EFAModel sharedInstance].loginInfo roleNameWithRoleId:roleId];
    if ([EFAModel sharedInstance].loginInfo.user_info.efairyrole_level == roleId) {
        NSString *title = [NSString stringWithFormat:@"恭喜您的角色已变更为%@", roleName];
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        UIViewController *topmostVC = [self topViewController];
        [topmostVC presentViewController:alertVC animated:YES completion:nil];
        return;
    } else {
        NSString *title = [NSString stringWithFormat:@"您的角色变更为%@, 请重新登录", roleName];
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:EFAGlobalNotiLogout object:nil];
        }]];
        UIViewController *topmostVC = [self topViewController];
        [topmostVC presentViewController:alertVC animated:YES completion:nil];
    }
}
- (void)jumpToUserNotice {
    UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [mainSb instantiateViewControllerWithIdentifier:@"EFAUtyPromptVC"];
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    UIViewController *topmostVC = [self topViewController];
    [topmostVC presentViewController:vc animated:YES completion:nil];
}
- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}
- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}
#pragma mark - network request
- (void)requestRefreshUserInfo {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMineUserCenter] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hideAnimated:NO];
        NSLog(@"请求用户信息返回：%@", responseObject);
        [[EFAModel sharedInstance] refreshUserInfoWithDictionary:responseObject];
        self.navEmptyVC = nil;
        [self setupSubViewsWithRefresh:NO];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求用户信息失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}
#pragma mark - getters and setters
- (UINavigationController *)navMsgVC {
    if (!_navMsgVC) {
        UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UIViewController *msgVC = [mainSb instantiateViewControllerWithIdentifier:@"EFAMsgVC"];
        _navMsgVC = [[UINavigationController alloc] initWithRootViewController:msgVC];
        _navMsgVC.tabBarItem.title = @"消息";
        _navMsgVC.tabBarItem.image = [UIImage imageNamed:@"rootvc_msg"];
        _navMsgVC.tabBarItem.selectedImage =[UIImage imageNamed:@"rootvc_msg_sel"];
    }
    return _navMsgVC;
}
- (UINavigationController *)navDeviceVC {
    if (!_navDeviceVC) {
        UIViewController *deviceVC;
//        if ([EFAModel sharedInstance].loginInfo.user_info.efairyrole_level == EFALoginUserRoleNormal) {
//            deviceVC = [[EFADeviceVC alloc] init];
//        } else {
//            deviceVC = [[EFAPjtManagerVC alloc] initWithViewType:EFAPjtManagerVCTypeDevice];
        deviceVC =[[ProjectListView alloc]init];
//        deviceVC = [[AddressChooseView alloc]init];
//        }
        _navDeviceVC = [[UINavigationController alloc] initWithRootViewController:deviceVC];
        _navDeviceVC.tabBarItem.title = @"设备";
        _navDeviceVC.tabBarItem.image = [UIImage imageNamed:@"rootvc_device"];
        _navDeviceVC.tabBarItem.selectedImage = [UIImage imageNamed:@"rootvc_device_sel"];
    }
    return _navDeviceVC;
}
- (UINavigationController *)navAppVC {
    if (!_navAppVC) {
        _navAppVC = [[UINavigationController alloc] initWithRootViewController:[[EFAAppVC alloc] init]];
        _navAppVC.tabBarItem.title = @"应用";
        _navAppVC.tabBarItem.image = [UIImage imageNamed:@"rootvc_app"];
        _navAppVC.tabBarItem.selectedImage = [UIImage imageNamed:@"rootvc_app_sel"];
    }
    return _navAppVC;
}
- (UINavigationController *)navMoreVC {
    if (!_navMoreVC) {
        _navMoreVC = [[UINavigationController alloc] initWithRootViewController:[[EFAMoreVC alloc] init]];
        _navMoreVC.tabBarItem.title = @"我的";
        _navMoreVC.tabBarItem.image = [UIImage imageNamed:@"rootvc_more"];
        _navMoreVC.tabBarItem.selectedImage = [UIImage imageNamed:@"rootvc_more_sel"];
    }
    return _navMoreVC;
}
- (UINavigationController *)navEmptyVC {
    if (!_navEmptyVC) {
        _navEmptyVC = [[UINavigationController alloc] initWithRootViewController:[[UIViewController alloc] init]];
        _navEmptyVC.tabBarItem.title = @"设备";
        _navEmptyVC.tabBarItem.image = [UIImage imageNamed:@"rootvc_device"];
        _navEmptyVC.tabBarItem.selectedImage = [UIImage imageNamed:@"rootvc_device_sel"];
    }
    return _navEmptyVC;
}
@end
